<script>
import {Check, CircleCheck, Close, Delete, Edit, Plus, Search, SwitchButton, View} from "@element-plus/icons-vue";
import {nextTick} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {addApi, deleteApi, findAllApi, findByNameApi, updateApi} from "../api/unit.js";

export default {
  name: "UnitIndex",
  computed: {
    Search() {
      return Search
    },
    Plus() {
      return Plus
    },
    Close() {
      return Close
    },
    Check() {
      return Check
    },
    Delete() {
      return Delete
    },
    Edit() {
      return Edit
    },
    CircleCheck() {
      return CircleCheck
    },
    SwitchButton() {
      return SwitchButton
    }
  },
  components: {
    Search, Plus, Edit, View, SwitchButton,
    CircleCheck, Delete, Check, Close
  }
  ,data(){
    return{
      unitList: [
        { unitId: 1, unitName: '新鲜水果',convert:'0.5',status: '启用' },
      ],
      editCache:{},
      // 弹窗相关
      dialogVisible: false,
      unitName: '',
      convert:'',
      dialogLoading: false
    }
  },
  methods: {
    async loadData() {
      let {data:data} = await findAllApi();
      this.unitList = data.data
    },
    // 进入编辑状态
    handleEdit(row) {
      // 缓存当前数据
      this.editCache[row.unitId] = { ...row };
      // 设置编辑状态
      row.isEditing = true;

      // 确保输入框渲染后自动聚焦
      nextTick(() => {
        const input = this.$refs.editInput;
        if (input) input.focus();
      });
    },

    // 保存编辑内容
    async handleSave(row) {
      // 验证分类名称
      if (!row.unitName.trim()) {
        ElMessage.error('分类名称不能为空');
        return;
      }

      // 检查是否有实际修改
      const originalData = this.editCache[row.unitId];
      if (row.unitName === originalData.unitName) {
        row.isEditing = false;
        return;
      }

      try {
        row.loading = true;

        // 模拟API成功响应
        let {data:data} = await updateApi({
          unitId: row.unitId,
          unitName: row.unitName,
          status: row.status
        });
        if (data.code === 200) {
          ElMessage.success('修改成功');
          row.isEditing = false;
          delete this.editCache[row.unitId];
        } else {
          ElMessage.error(data.message || '修改失败');
          // 回滚数据
          row.unitName = originalData.unitName;
        }
      } catch (error) {
        console.error('修改失败:', error);
        ElMessage.error('网络异常，修改失败');
        // 回滚数据
        row.unitName = originalData.unitName;
      } finally {
        row.loading = false;
      }
    },

    // 取消编辑
    handleCancel(row) {
      // 恢复原始数据
      const originalData = this.editCache[row.unitId];
      if (originalData) {
        row.unitName = originalData.unitName;
      }
      row.isEditing = false;
      delete this.editCache[row.unitId];
    },
    // 切换状态 (0:停用, 1:启用)
    async handleToggleStatus(row) {
      const originalStatus = row.status;
      const newStatus = originalStatus === 1 ? 0 : 1; // 1→0 启用→停用，0→1 停用→启用

      try {
        row.loading = true;
        // 调用API更新状态
        let {data:data} = await updateApi({
          unitId: row.unitId,
          status: newStatus
        });
        console.log(data)
        if (data.code === 200) {
          row.status = newStatus;
          ElMessage.success(`已${newStatus === 1 ? '启用' : '停用'}该分类`);
        } else {
          ElMessage.error(data.message || '状态更新失败');
          row.status = originalStatus; // 回滚状态
        }
      } catch (error) {
        console.error('状态更新失败:', error);
        ElMessage.error('网络异常，状态更新失败');
        row.status = originalStatus; // 回滚状态
      } finally {
        row.loading = false;
      }
    },

    // 搜索功能
    async handleSearch() {
      console.log('搜索:', this.unitList.unitName);
      let {data:data} = await findByNameApi(this.unitList.unitName);
      console.log(data)
      this.unitList = [data.data]
    },

    // 添加计量单位
    handleAdd() {
      // 重置表单
      this.unitName = '';
      this.convert = '';
      // 显示弹窗
      this.dialogVisible = true;
    },

    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
    },

    // 保存子类别
    async saveChildCategory() {
      // 验证
      if (!this.unitName.trim()) {
        ElMessage.error('计量单位不能为空');
        return;
      }

      try {
        this.dialogLoading = true;

        const {data:data} = await addApi({
          unitName: this.unitName,
          convert: this.convert  //
        });
        console.log(data)
        if (data.code === 200) {
          ElMessage.success('计量单位添加成功');
          this.dialogVisible = false;
          // 重新加载数据
          await this.loadData();
        } else {
          ElMessage.error(data.message || '添加失败');
        }
      } catch (error) {
        console.error('添加子类别失败:', error);
        ElMessage.error('网络异常，添加失败');
      } finally {
        this.dialogLoading = false;
      }
    },
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm(
            `确定要删除 ${row.name} 吗？`,
            '删除确认',
            {type: 'warning'}
        )
        let {data: data} = await deleteApi(row.unitId);
        await this.loadData()
        this.$emit('refresh') // 触发父组件刷新数据
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.message || '删除失败')
        }
      }

    },
  },
  mounted() {
    this.loadData()
  }
}
</script>

<template>
  <div class="unit-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input
          v-model="unitList.unitName"
          placeholder="请输入分类名称"
          clearable
          style="width: 300px; margin-right: 10px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
      <el-button type="success" @click="handleAdd" :icon="Plus">添加计量单位</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
        :data="unitList"
        style="width: 100%; margin-top: 20px"
        border
        stripe
    >
      <el-table-column prop="unitId" label="序号" width="80" align="center" />
      <el-table-column label="单位名" width="180">
        <template #default="{ row }">
          <!-- 编辑状态显示输入框，否则显示文本 -->
          <template v-if="row.isEditing">
            <el-input
                v-model="row.unitName"
                size="small"
                @blur="handleSave(row)"
                @keyup.enter="handleSave(row)"
                ref="editInput"
                class="edit-input"
            />
          </template>
          <template v-else>
            {{ row.unitName }}
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="convert" label="换算" width="80" align="center" />
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="350px" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <!-- 编辑状态切换按钮组 -->
            <el-button
                v-if="!row.isEditing"
                type="primary"
                size="small"
                @click="handleEdit(row)"
                :icon="Edit"
                :disabled="row.loading"
            >
              编辑
            </el-button>
            <el-button
                v-if="row.isEditing"
                type="success"
                size="small"
                @click="handleSave(row)"
                :icon="Check"
            >
              保存
            </el-button>
            <el-button
                v-if="row.isEditing"
                type="warning"
                size="small"
                @click="handleCancel(row)"
                :icon="Close"
            >
              取消
            </el-button>

            <el-button
                :type="row.status === 1 ? 'warning' : 'success'"
                size="small"
                @click="handleToggleStatus(row)"
                :icon="row.status === 1 ? SwitchButton : CircleCheck"
                :disabled="row.isEditing || row.loading"
                :loading="row.loading"
            >
              {{ row.status === 1 ? '停用' : '启用' }}
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
                :icon="Delete"
                :disabled="row.isEditing || row.loading"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 子类别添加弹窗 -->
    <el-dialog
        title="添加子类别"
        v-model="dialogVisible"
        width="400px"
        :before-close="closeDialog"
    >
      <el-form>
        <el-form-item label="单位名" label-width="100px" required>
          <el-input
              v-model="unitName"
              placeholder="请输入计量单位名称"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="换算单位" label-width="100px" required>
          <el-input
              v-model="convert"
              placeholder="请输入换算单位"
              clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveChildCategory" :loading="dialogLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.category-management {
  padding: 20px;
}

.search-container {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
/* 黄色背景标记的新增样式 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>